package com.su.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.AMQP;

import com.rabbitmq.client.Channel;
import com.su.common.to.OrderTo;
import com.su.common.to.mq.StockDetailTo;
import com.su.common.to.mq.StockLockedTo;
import com.su.common.utils.R;
import com.su.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.su.gulimall.ware.entity.WareOrderTaskEntity;
import com.su.gulimall.ware.exception.NoStockException;
import com.su.gulimall.ware.feign.OrderFeignService;
import com.su.gulimall.ware.feign.ProductFeignService;
import com.su.gulimall.ware.service.WareOrderTaskDetailService;
import com.su.gulimall.ware.service.WareOrderTaskService;
import com.su.gulimall.ware.vo.*;
import lombok.Data;
import org.omg.SendingContext.RunTime;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.su.common.utils.PageUtils;
import com.su.common.utils.Query;

import com.su.gulimall.ware.dao.WareSkuDao;
import com.su.gulimall.ware.entity.WareSkuEntity;
import com.su.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    WareOrderTaskService wareOrderTaskService;
    @Autowired
    OrderFeignService orderFeignService;

    /*
     * 库存解锁的场景：
     * 场景一：下订单成功，订单过期没有支付被系统自动取消；订单下单完成后被用户手动取消
     * 场景二：下订单成功，库存锁定成功，但是由于其他业务失败，导致订单回滚，之前锁定的库存就要自动解锁
     * */
    //处理消息的方法:只要解锁库存消息被处理，队列就会删除，但是解锁操作可能会出现问题，此时没有解锁消息，这是不合理的)
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        //通过两个参数对其进行相关的查找
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities == null || entities.size() == 0) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");

                if (info.getCode() == 0) {
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }


            wareSkuDao.insert(skuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> vos = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前库存，大于0时返回
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStockVo(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }

    /*
     * 库存解锁场景：
     * 场景一：下单成功，订单超时没有支付此时解锁库存；订单被用户手动取消
     * 场景二：下订单成功，库存锁定成功，其他业务调用失败，导致订单回滚，之前锁定的库存就要解锁
     * */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        //1.商品在哪个仓库，所有仓库还有多少件可以买，如果够，锁定
        //第一步，商品在哪个仓库有库存
        //将订单锁定的任务信息进行保存（哪个订单需要锁定）
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);
        //获取需要锁定的订单项
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            //封装一个实体类，获取需要锁的订单项的id，
            //该订单项数量，以及锁在哪个仓库
            SkuWareHasStock hasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            hasStock.setSkuId(skuId);
            //哪个仓库里还可以锁定该sku商品（数量上还能锁定）
            List<Long> wareIds = wareSkuDao.listWareIdHasStock(skuId);
            hasStock.setWareId(wareIds);
            //需要锁定的数量
            hasStock.setNum(item.getCount());
            return hasStock;
        }).collect(Collectors.toList());
        //第二步，锁定仓库的库存
        for (SkuWareHasStock hasStock : collect) {
            //是否锁定成功的状态码
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                //没有任何一个仓库中可以存储该号商品直接抛出异常
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                //尝试锁定库存，成功返回1.失败返回1；
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    //锁定库存成功
                    skuStocked = true;
                    //todo:告诉mq,库存锁定成功
                    //将商品的锁定信息存储在详情表中，便于回滚
                    //锁的哪个商品，锁了几件，锁在哪个仓库，属于哪个订单业务
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
                    detailEntity.setSkuId(hasStock.skuId);
                    detailEntity.setSkuNum(hasStock.getNum());
                    detailEntity.setWareId(wareId);
                    detailEntity.setTaskId(taskEntity.getId());
                    detailEntity.setLockStatus(1);
                    wareOrderTaskDetailService.save(detailEntity);
                    //封装：锁定哪个订单；锁定细节id;根据这个类进行回滚，发送给mq
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity, detailTo);
                    //属性的对拷
                    //有可能出现部分库存锁定失败，锁定的数据进行回滚，但是消息已经发出的情况
                    lockedTo.setDetail(detailTo);
                    //发送消息，库存锁定成功，消息会进入延时队列，一段时间消息死亡，
                    //查询订单状态，符合解锁要求，自动解锁库存（时间略大于订单的自动关闭时间）
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo);
                    break;
                } else {
                    //当前仓库锁定失败，重试下一个仓库
                }
            }
            if (skuStocked == false) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
        //全部锁定成功
        return true;
    }
    //库存解锁的补偿逻辑
    @Override
    public void unlockStock(StockLockedTo lockedTo) {
        StockDetailTo detail = lockedTo.getDetail();
        Long detailId = detail.getId();
        //查询数据库关于这个订单的库存锁定信息
        //如果有：
        //所有商品库存锁定成功，
        //如果没有：库存锁定失败，可能存在部分商品锁定失败问题
        //锁定成功的商品发送了消息，但是由于整体事务回滚，数据已经被清除，无需解锁；
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);
        if (detailEntity != null) {
            //所有库存锁定成功：需要观察整体业务是否成功，
            //解锁情况：
            //情况一:没有这个订单，必须解锁；(订单回滚)
            //情况二:有这个订单：查看订单状态，如果订单处于取消状态，解锁库存，其余所有状态均不解锁库存
            Long id = lockedTo.getId();
            WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(id);
            String orderSn = orderTaskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderVo data = (OrderVo) r.getData(new TypeReference<OrderVo>() {
                });
                if (data == null || data.getStatus() == 4) {
                    //订单处于被取消状态,此时将其库存数量更新即可
                    if(detailEntity.getLockStatus()==1) {
                        //状态1：库存处于锁定状态，但是未解锁，才可以进行解锁，
                        //如果库存工作单处于已解锁状态，此时
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            }else {
                //远程服务调用出现问题
                throw  new RuntimeException("远程服务失败");
            }
        }
    }
    //库存解锁的主逻辑
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下库存的解锁情况
        WareOrderTaskEntity taskEntity=wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = taskEntity.getId();
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : list) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getTaskId());
        }
    }

    //库存解锁的真正方法
    private void unLockStock(Long skuId, Long wareId, Integer num,Long taskDetailId) {
        //解锁库存的锁定数量
        wareSkuDao.unLockStock(skuId, wareId, num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity orderTaskDetailEntity = new WareOrderTaskDetailEntity();
        orderTaskDetailEntity.setLockStatus(2);
        orderTaskDetailEntity.setId(taskDetailId);
        wareOrderTaskDetailService.updateById(orderTaskDetailEntity);
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }
}